package com.eedi.framework.dict.service;

import cn.hutool.core.collection.CollUtil;
import com.google.common.annotations.VisibleForTesting;
import com.eedi.framework.dict.controller.sys.vo.data.SysDictDataResp;
import com.eedi.framework.dict.controller.sys.vo.data.SysDictDataSaveReq;
import com.eedi.framework.dict.dal.dataobject.SysDictDataDO;
import com.eedi.framework.dict.dal.dataobject.SysDictTypeDO;
import com.eedi.framework.dict.dal.mapper.SysDictDataMapper;
import com.eedi.framework.common.enums.CommonStatusEnum;
import com.eedi.framework.common.pojo.PageResult;
import com.eedi.framework.common.util.collection.CollectionUtils;
import com.eedi.framework.common.util.object.BeanUtils;
import com.eedi.framework.dict.controller.sys.vo.data.SysDictDataPageReq;
import com.eedi.framework.dict.controller.sys.vo.data.SysDictDataUpReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static com.eedi.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.eedi.framework.dict.enums.SysDictErrorCodeConstants.*;

/**
 * 字典数据 Service 实现类
 *
 */
@Service
@Slf4j
public class SysDictDataServiceImpl implements SysDictDataService {

    /**
     * 排序 dictType > sort
     */
    private static final Comparator<SysDictDataDO> COMPARATOR_TYPE_AND_SORT = Comparator
            .comparing(SysDictDataDO::getSysDictType)
            .thenComparingInt(SysDictDataDO::getSysDictDataSort);

    @Resource
    private SysDictTypeService sysDictTypeService;

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public List<SysDictDataDO> getDictDataList(CommonStatusEnum status, String dictType) {
        List<SysDictDataDO> list = sysDictDataMapper.selectListByStatusAndDictType(status, dictType);
        list.sort(COMPARATOR_TYPE_AND_SORT);
        return list;
    }

    @Override
    public Map<String, List<SysDictDataResp>> getDictDataMap(Set<String> sysDictDataType) {
        if (CollUtil.isEmpty(sysDictDataType)){
            return Map.of();
        }
        return sysDictDataMapper.getDictDataMap(sysDictDataType);
    }

    @Override
    public List<SysDictDataResp> getDictDataList(Set<String> sysDictDataType) {
        if (CollUtil.isEmpty(sysDictDataType)){
            return List.of();
        }
        return sysDictDataMapper.getDictDataList(sysDictDataType);
    }

    @Override
    public PageResult<SysDictDataDO> getDictDataPage(SysDictDataPageReq pageReqVO) {
        return sysDictDataMapper.selectPage(pageReqVO);
    }

    @Override
    public SysDictDataDO getDictData(String id) {
        return sysDictDataMapper.selectById(id);
    }

    @Override
    public String createDictData(SysDictDataSaveReq createReqVO) {
        // 校验字典类型有效
        validateDictTypeExists(createReqVO.getSysDictType());
        // 校验字典数据的值的唯一性
        validateDictDataValueUnique(null, createReqVO.getSysDictType(), createReqVO.getSysDictValue());

        // 插入字典类型
        SysDictDataDO dictData = BeanUtils.toBean(createReqVO, SysDictDataDO.class);
        sysDictDataMapper.insert(dictData);
        return dictData.getSysDictDataId();
    }

    @Override
    public void updateDictData(SysDictDataUpReq updateReqVO) {
        // 校验自己存在
        validateDictDataExists(updateReqVO.getSysDictDataId());
        // 校验字典类型有效
        validateDictTypeExists(updateReqVO.getSysDictType());
        // 校验字典数据的值的唯一性
        validateDictDataValueUnique(updateReqVO.getSysDictDataId(), updateReqVO.getSysDictType(), updateReqVO.getSysDictValue());

        // 更新字典类型
        SysDictDataDO updateObj = BeanUtils.toBean(updateReqVO, SysDictDataDO.class);
        sysDictDataMapper.updateById(updateObj);
    }

    @Override
    public void deleteDictData(String id) {
        // 校验是否存在
        validateDictDataExists(id);

        // 删除字典数据
        sysDictDataMapper.deleteById(id);
    }

    @Override
    public long getDictDataCountByDictType(String dictType) {
        return sysDictDataMapper.selectCountByDictType(dictType);
    }

    @VisibleForTesting
    public void validateDictDataValueUnique(String id, String dictType, String value) {
        SysDictDataDO dictData = sysDictDataMapper.selectByDictTypeAndValue(dictType, value);
        if (dictData == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的字典数据
        if (id == null) {
            throw exception(SYS_DICT_DATA_VALUE_DUPLICATE);
        }
        if (!dictData.getSysDictDataId().equals(id)) {
            throw exception(SYS_DICT_DATA_VALUE_DUPLICATE);
        }
    }

    @VisibleForTesting
    public void validateDictDataExists(String id) {
        if (id == null) {
            return;
        }
        SysDictDataDO dictData = sysDictDataMapper.selectById(id);
        if (dictData == null) {
            throw exception(SYS_DICT_DATA_NOT_EXISTS);
        }
    }

    @VisibleForTesting
    public void validateDictTypeExists(String type) {
        SysDictTypeDO dictType = sysDictTypeService.getDictType(type);
        if (dictType == null) {
            throw exception(SYS_DICT_TYPE_NOT_EXISTS);
        }
        if (!CommonStatusEnum.ENABLE.equals(dictType.getSysDictDataStatus())) {
            throw exception(SYS_DICT_TYPE_NOT_ENABLE);
        }
    }

    @Override
    public void validateDictDataList(String dictType, Collection<String> values) {
        if (CollUtil.isEmpty(values)) {
            return;
        }
        Map<String, SysDictDataDO> dictDataMap = CollectionUtils.convertMap(
                sysDictDataMapper.selectByDictTypeAndValues(dictType, values), SysDictDataDO::getSysDictValue);
        // 校验
        values.forEach(value -> {
            SysDictDataDO dictData = dictDataMap.get(value);
            if (dictData == null) {
                throw exception(SYS_DICT_DATA_NOT_EXISTS);
            }
            if (!CommonStatusEnum.ENABLE.equals(dictData.getSysDictDataStatus())) {
                throw exception(SYS_DICT_DATA_NOT_ENABLE, dictData.getSysDictLabel());
            }
        });
    }

    @Override
    public SysDictDataDO getDictData(String dictType, String value) {
        return sysDictDataMapper.selectByDictTypeAndValue(dictType, value);
    }

    @Override
    public SysDictDataDO parseDictData(String dictType, String label) {
        return sysDictDataMapper.selectByDictTypeAndLabel(dictType, label);
    }

    @Override
    public List<SysDictDataDO> getDictDataByType(String dictType) {
        return null;
    }

}
